﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace XamlDom.Runtime
{
    public class ClrObjectRuntime
    {
        #region Sigleton

        private static ClrObjectRuntime _instance;

        private ClrObjectRuntime()
        {

        }

        public static ClrObjectRuntime Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ClrObjectRuntime();
                }
                return _instance;
            }
        }

        #endregion
      
        /// <summary>
        /// 创建对象实例
        /// </summary>
        /// <param name="type"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public object CreateInstance(Type type, object[] args)
        {
            return Activator.CreateInstance(type, args);
        }

        /// <summary>
        /// 设置对象属性
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="propertyName"></param>
        /// <param name="value"></param>
        public void SetPropertyValue(object instance, string propertyName, string value)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(instance);
            PropertyDescriptor descriptor = properties[propertyName];
            if (descriptor != null)
            {
                object propertyValue = descriptor.Converter.ConvertFromString(value);
                descriptor.SetValue(instance, propertyValue);
            }
        }

        public DependencyProperty FindAttachedProperty(Type type, string dependencyPropertyName)
        {
            MethodInfo getMethod = type.GetMethod("Get" + dependencyPropertyName, BindingFlags.Public | BindingFlags.Static);
            MethodInfo setMethod = type.GetMethod("Set" + dependencyPropertyName, BindingFlags.Public | BindingFlags.Static);

            if (getMethod != null && setMethod != null)
            {
                FieldInfo fieldInfo = type.GetField(dependencyPropertyName + "Property", BindingFlags.Public | BindingFlags.Static);
                if (fieldInfo != null && fieldInfo.FieldType == typeof(DependencyProperty))
                {
                    return (DependencyProperty)fieldInfo.GetValue(null) ;
                }
            }
            return null;
        }
    }
}
